<?php
/**
 * 预约挂号页面
 * 州弟医院信息系统 - 州弟学安全
 */

// 包含头文件
include 'includes/header.php';

// 检查用户是否已登录
if (!isLoggedIn()) {
    $_SESSION['error_msg'] = '请先登录后再进行预约挂号';
    redirect('login.php');
}

// 检查用户是否为患者
if (!hasRole('patient')) {
    $_SESSION['error_msg'] = '只有患者账号可以进行预约挂号';
    redirect('index.php');
}

// 获取所有科室
$departments = getAllDepartments();

// 处理预约表单提交
$error = '';
$success = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $department_id = $_POST['department'] ?? '';
    $doctor_id = $_POST['doctor'] ?? '';
    $appointment_date = $_POST['appointment_date'] ?? '';
    $appointment_time = $_POST['appointment_time'] ?? '';
    $symptoms = $_POST['symptoms'] ?? '';
    
    // 基本验证
    if (empty($department_id) || empty($doctor_id) || empty($appointment_date) || empty($appointment_time)) {
        $error = '请填写所有必填字段';
    } else {
        // 获取患者ID
        $user_id = $_SESSION['user_id'];
        $sql = "SELECT id FROM patients WHERE user_id = $user_id";
        $result = $conn->query($sql);
        
        if ($result && $result->num_rows > 0) {
            $patient = $result->fetch_assoc();
            $patient_id = $patient['id'];
            
            // 整合日期和时间
            $appointment_datetime = $appointment_date . ' ' . $appointment_time . ':00';
            
            // 检查医生在指定时间是否已有预约
            $appointment_datetime = $conn->real_escape_string($appointment_datetime);
            $sql = "SELECT * FROM appointments 
                    WHERE doctor_id = $doctor_id 
                    AND appointment_time = '$appointment_datetime' 
                    AND status != '已取消'";
            $result = $conn->query($sql);
            
            if ($result && $result->num_rows > 0) {
                $error = '该时间段医生已有预约，请选择其他时间';
            } else {
                // 插入预约记录
                $department_id = (int)$department_id;
                $doctor_id = (int)$doctor_id;
                $symptoms = $conn->real_escape_string($symptoms);
                
                $sql = "INSERT INTO appointments (patient_id, doctor_id, department_id, appointment_time, symptoms, status) 
                        VALUES ($patient_id, $doctor_id, $department_id, '$appointment_datetime', '$symptoms', '待确认')";
                
                if ($conn->query($sql)) {
                    $appointment_id = $conn->insert_id;
                    
                    // 记录预约日志
                    logAction($user_id, '创建预约（预约ID：' . $appointment_id . '）');
                    
                    $success = '预约挂号成功！请等待医生确认。';
                } else {
                    $error = '预约挂号失败：' . $conn->error;
                }
            }
        } else {
            $error = '未找到患者信息，请完善个人资料';
        }
    }
}
?>

<div class="row">
    <div class="col-md-8">
        <div class="card">
            <div class="card-header">
                <h4 class="mb-0">在线预约挂号</h4>
            </div>
            <div class="card-body">
                <?php if ($error): ?>
                    <div class="alert alert-danger"><?php echo $error; ?></div>
                <?php endif; ?>
                
                <?php if ($success): ?>
                    <div class="alert alert-success"><?php echo $success; ?></div>
                    <p class="text-center">
                        <a href="patient/appointments.php" class="btn btn-primary">查看我的预约</a>
                        <a href="appointment.php" class="btn btn-outline-primary ml-2">继续预约</a>
                    </p>
                <?php else: ?>
                    <form method="post" action="appointment.php" class="appointment-form needs-validation" novalidate>
                        <div class="form-group">
                            <label for="department">选择科室 <span class="text-danger">*</span></label>
                            <select class="form-control" id="department" name="department" required>
                                <option value="">请选择科室</option>
                                <?php foreach ($departments as $dept): ?>
                                    <option value="<?php echo $dept['id']; ?>"><?php echo $dept['name']; ?> (<?php echo $dept['floor']; ?>)</option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label for="doctor">选择医生 <span class="text-danger">*</span></label>
                            <select class="form-control" id="doctor" name="doctor" required disabled>
                                <option value="">请先选择科室</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label for="appointment_date">预约日期 <span class="text-danger">*</span></label>
                            <input type="date" class="form-control datepicker" id="appointment_date" name="appointment_date" required min="<?php echo date('Y-m-d'); ?>">
                            <small class="form-text text-muted">请选择今天之后的日期</small>
                        </div>
                        
                        <div class="form-group">
                            <label for="appointment_time">预约时间 <span class="text-danger">*</span></label>
                            <select class="form-control" id="appointment_time" name="appointment_time" required>
                                <option value="">请选择时间</option>
                                <option value="08:00">08:00</option>
                                <option value="08:30">08:30</option>
                                <option value="09:00">09:00</option>
                                <option value="09:30">09:30</option>
                                <option value="10:00">10:00</option>
                                <option value="10:30">10:30</option>
                                <option value="11:00">11:00</option>
                                <option value="11:30">11:30</option>
                                <option value="14:00">14:00</option>
                                <option value="14:30">14:30</option>
                                <option value="15:00">15:00</option>
                                <option value="15:30">15:30</option>
                                <option value="16:00">16:00</option>
                                <option value="16:30">16:30</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label for="symptoms">症状描述</label>
                            <textarea class="form-control" id="symptoms" name="symptoms" rows="4" placeholder="请简要描述您的症状和不适情况，以便医生提前了解"></textarea>
                        </div>
                        
                        <div class="form-group form-check">
                            <input type="checkbox" class="form-check-input" id="confirm_info" required>
                            <label class="form-check-label" for="confirm_info">我确认以上信息真实无误</label>
                        </div>
                        
                        <div class="text-center mt-4">
                            <button type="submit" class="btn btn-primary btn-lg">提交预约</button>
                        </div>
                    </form>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <div class="col-md-4">
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0">预约须知</h5>
            </div>
            <div class="card-body">
                <ul class="mb-0">
                    <li>请提前3天进行预约</li>
                    <li>请按时就诊，如需取消请提前通知</li>
                    <li>初诊患者请携带身份证、医保卡等有效证件</li>
                    <li>复诊患者请携带病历卡和相关检查资料</li>
                    <li>预约成功后，请在预约时间前30分钟到医院</li>
                </ul>
            </div>
        </div>
        
        <div class="card">
            <div class="card-header bg-light">
                <h5 class="mb-0">就诊流程</h5>
            </div>
            <div class="card-body p-0">
                <div class="list-group list-group-flush">
                    <div class="list-group-item">
                        <i class="fas fa-laptop text-primary mr-2"></i>
                        <strong>1. 线上预约</strong>
                        <p class="mb-0 mt-1 small text-muted">在系统中选择科室、医生和时间</p>
                    </div>
                    <div class="list-group-item">
                        <i class="fas fa-check-circle text-primary mr-2"></i>
                        <strong>2. 预约确认</strong>
                        <p class="mb-0 mt-1 small text-muted">医生确认预约后，系统将通知您</p>
                    </div>
                    <div class="list-group-item">
                        <i class="fas fa-hospital text-primary mr-2"></i>
                        <strong>3. 医院就诊</strong>
                        <p class="mb-0 mt-1 small text-muted">按时到医院，凭预约号到导诊台</p>
                    </div>
                    <div class="list-group-item">
                        <i class="fas fa-stethoscope text-primary mr-2"></i>
                        <strong>4. 医生诊断</strong>
                        <p class="mb-0 mt-1 small text-muted">按顺序进入诊室，医生为您诊断</p>
                    </div>
                    <div class="list-group-item">
                        <i class="fas fa-notes-medical text-primary mr-2"></i>
                        <strong>5. 取药/检查</strong>
                        <p class="mb-0 mt-1 small text-muted">根据医嘱到相应窗口取药或检查</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// AJAX获取医生列表的函数
document.addEventListener('DOMContentLoaded', function() {
    // 科室选择联动
    var departmentSelect = document.getElementById('department');
    var doctorSelect = document.getElementById('doctor');
    
    if (departmentSelect) {
        departmentSelect.addEventListener('change', function() {
            var departmentId = this.value;
            if (departmentId) {
                // 启用医生选择
                doctorSelect.disabled = true;
                doctorSelect.innerHTML = '<option value="">加载中...</option>';
                
                // AJAX请求医生列表
                var xhr = new XMLHttpRequest();
                xhr.open('POST', 'get_doctors.php', true);
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                xhr.onload = function() {
                    if (xhr.status === 200) {
                        try {
                            var doctors = JSON.parse(xhr.responseText);
                            var options = '<option value="">请选择医生</option>';
                            
                            for (var i = 0; i < doctors.length; i++) {
                                options += '<option value="' + doctors[i].id + '">' + 
                                           doctors[i].name + ' - ' + doctors[i].position + 
                                           '</option>';
                            }
                            
                            doctorSelect.innerHTML = options;
                            doctorSelect.disabled = false;
                        } catch (e) {
                            doctorSelect.innerHTML = '<option value="">加载失败，请重试</option>';
                        }
                    } else {
                        doctorSelect.innerHTML = '<option value="">加载失败，请重试</option>';
                    }
                };
                
                xhr.onerror = function() {
                    doctorSelect.innerHTML = '<option value="">网络错误，请重试</option>';
                };
                
                xhr.send('department_id=' + departmentId);
            } else {
                // 重置医生选择
                doctorSelect.innerHTML = '<option value="">请先选择科室</option>';
                doctorSelect.disabled = true;
            }
        });
    }
    
    // 设置日期最小值为今天
    var appointmentDateInput = document.getElementById('appointment_date');
    if (appointmentDateInput) {
        var today = new Date();
        var dd = String(today.getDate()).padStart(2, '0');
        var mm = String(today.getMonth() + 1).padStart(2, '0');
        var yyyy = today.getFullYear();
        
        today = yyyy + '-' + mm + '-' + dd;
        appointmentDateInput.min = today;
    }
});
</script>

<?php
// 包含尾文件
include 'includes/footer.php';
?> 